<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <div :class="advanced ? null: 'fold'">
          <a-row>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="法人行"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 18, offset: 1}">
                <a-select
                          mode="default"
                          :allowClear="true"
                          style="width: 100%"
                          @change="handleInstChange"
                          v-model="queryParams.instId">
                  <a-select-option v-for="r in instIdData" :key="r.label">{{r.label}}-{{r.value}}</a-select-option>
                </a-select>
<!--                <a-input v-if="!this.user.admin" v-model="queryParams.instId" :value="this.user.instId"
                         readonly="readonly"/>-->
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" v-show="queryParams.instId!=''">
              <a-form-item
                label="收单机构号"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 18, offset: 1}">
                <a-select
                  show-search
                  placeholder="请输入代码或名称"
                  option-filter-prop="children"
                  style="width: 100%"
                  :filter-option="filterOption"
                  @focus="selectSignInstId"
                  v-model="queryParams.signInstId"
                >
                  <a-select-option v-for="(d,index) in signInstIdData" :key="d.id">
                    {{ d.id }}-{{d.name}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="queryParams.instId!=''">
            <a-col :md="12" :sm="24">
              <a-form-item label="商户号"
                           :labelCol="{span: 5}"
                           :wrapperCol="{span: 18, offset: 1}">
                <a-input v-model="queryParams.mchntNo"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="商户名称"
                           :labelCol="{span: 5}"
                           :wrapperCol="{span: 18, offset: 1}">
                <a-input v-model="queryParams.mchntName"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="queryParams.instId!=''">
            <a-col :md="12" :sm="24">
              <a-form-item
                label="延迟状态"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 18, offset: 1}">
                <a-select
                  mode="default"
                  :allowClear="true"
                  style="width: 100%"
                  show-search
                  placeholder="请选择"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  v-model="queryParams.mchntDelayFlag">
                  <a-select-option key="Y">延迟清算</a-select-option>
                  <a-select-option key="N">解除延迟</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div style="text-align: center;margin-bottom: 20px" v-show="queryParams.instId!=''">
          <a-button type="primary" @click="search">查询</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
        </div>
      </a-form>
    </div>
    <div v-show="queryParams.instId!=''">
      <!-- 表格区域 -->
      <a-table ref="TableInfo"
               :columns="columns"
               :rowKey="record => record.id"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               :scroll="{ x: 1200 }"
               @change="handleTableChange">
        <template slot="email" slot-scope="text, record">
          <a-popover placement="topLeft">
            <template slot="content">
              <div>{{text}}</div>
            </template>
            <p style="width: 150px;margin-bottom: 0">{{text}}</p>
          </a-popover>
        </template>
        <template slot="merchantDelayOperation" slot-scope="text, record">
          <a-icon v-hasPermission="['merchantDelay:stop']" type="setting" theme="twoTone" twoToneColor="#4a9ff5"
                  @click="editMerchantDelay(record)" title="新增延迟清算"></a-icon>&nbsp;
          <a-icon v-hasPermission="['merchantDelay:remove']" type="stop" theme="twoTone" twoToneColor="#42b983"
                  @click="viewMerchantDelay(record)" title="解除延迟"></a-icon>
          <a-badge v-hasNoPermission="['merchantDelay:stop','merchantDelay:remove']" userStatus="warning" text="无权限"></a-badge>
        </template>

      </a-table>
      <!-- 新增延迟清算 -->
      <merchant-delay-operation
        ref="merchantDelayEdit"
        @close="handleMerchantDelayInfoClose"
        @success="handleMerchantDelayInfoSuccess"
        :merchantDelayInfoVisiable="merchantDelayOperation.visiable">
      </merchant-delay-operation>

    </div>

    <div>
      <a-modal
        title="确认操作"
        :visible="isShow"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        确定解除延迟吗？
      </a-modal>
    </div>
  </a-card>
</template>

<script>
  import RangeDate from '@/components/datetime/RangeDate'
  import MerchantDelayOperation from "./MerchantDelayOperation";
  import {mapState} from "vuex"

  export default {
    name: "MerchantDelay",
    components: {MerchantDelayOperation, RangeDate},
    data() {
      return {
        tempId: '',
        isShow: false,
        advanced: false,
        merchantDelayOperation: {
          visiable: false,
        },
        signInstIdData: [],
        queryParams: {
          signInstId: '',
          mchntDelayFlag: '',
          mchntName: '',
          mchntNo: '',
          instId: ''
        },
        dataSource: [],
        sortedInfo: null,
        paginationInfo: null,
        selectedRowKeys: [],
        pagination: {
          pageSizeOptions: ['10', '20', '30', '40', '100'],
          defaultCurrent: 1,
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
        },
        loading: false,
        instIdData: [],
        da: []
      }
    },
    computed: {
      ...mapState({
        user: state => state.account.user,

      }),
      columns() {
        let {sortedInfo} = this
        sortedInfo = sortedInfo || {}
        let {filteredInfo} = this
        filteredInfo = filteredInfo || {}
        return [{
          title: '收单机构',
          dataIndex: 'signInstId',
          scopedSlots: {customRender: 'signInstId'},
        }, {
          title: '商户号',
          dataIndex: 'mchntNo',
          scopedSlots: {customRender: 'mchntNo'},
          width:200
        }, {
          title: '商户名称',
          dataIndex: 'mchntName',
          scopedSlots: {customRender: 'mchntName'},
          width:200
        }, {
          title: '商户类型',
          dataIndex: 'mchntType',
          customRender: (text, row, index) => {
            switch (text) {
              case '00':
                return <a-tag color = "cyan" > 普通商户 < /a-tag>
              case '10':
                return <a-tag color = "pink" > 连锁商户 < /a-tag>
              case '11':
                return <a-tag color = "pink" > 连锁商户门店 < /a-tag>
              case '20':
                return <a-tag color = "pink" > 小微商户 < /a-tag>
              default:
                return text
            }
          },
          filters: [
            {text: '普通商户', value: '00'},
            {text: '连锁商户', value: '10'},
            {text: '连锁商户门店', value: '11'},
            {text: '小微商户', value: '20'}
          ],
          filterMultiple: false,
          filteredValue: filteredInfo.mchntType || null,
          onFilter: (value, record) => record.mchntType.includes(value)
        }, {
          title: '延迟状态',
          dataIndex: 'mchntDelayFlag',
          customRender: (text, row, index) => {
            switch (text) {
              case 'Y':
                return <a-tag color = "cyan" > 延迟清算 < /a-tag>
              case 'N':
                return <a-tag color = "pink" > 解除延迟 < /a-tag>
              default:
                return text
            }
          },
          filters: [
            {text: '延迟清算', value: 'Y'},
            {text: '解除延迟', value: 'S'},
          ],
          filterMultiple: false,
          filteredValue: filteredInfo.mchntDelayFlag || null,
          onFilter: (value, record) => record.mchntDelayFlag.includes(value)
        }, {
          title: '已延迟清算总金额（元）',
          dataIndex: 'remark1',
          scopedSlots: {customRender: 'remark1'},
          width: 200
        }, {
          title: '延迟原因',
          dataIndex: 'mchntDelayResaon',
          scopedSlots: {customRender: 'mchntDelayResaon'},

        }, {
          title: '操作',
          dataIndex: 'merchantDelayOperation',
          fixed: 'right',
          scopedSlots: {customRender: 'merchantDelayOperation'}
        }]
      }
    },
    mounted() {
      this.$get('admin/upmporg/getInstList').then((r) => {
        this.instIdData = r.data
      })
    },
    methods: {
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys
      },

      selectSignInstId(val) {
        this.signInstIdData = []
        let param = {}
        if (val) {
          param = {
            q: encodeURIComponent(val + `&${this.queryParams.instId}`),
            pageSize: 20
          }
          if (val.length >= 5) {
            this.$get('/admin/merParam/UpmpOrganization/instIdOrganizationSelect2List', param).then((r) => {
              let result = r.data.results
              result.forEach(r => {
                this.signInstIdData.push(r);
              })
            })
          }
        } else {
          param = {
            q: encodeURIComponent(`&${this.queryParams.instId}`),
            pageSize: 20
          }
          this.$get('/admin/merParam/UpmpOrganization/instIdOrganizationSelect2List', param).then((r) => {
            let result = r.data.results
            result.forEach(r => {
              this.signInstIdData.push(r);
            })
          })
        }

      },

      handleInstChange(value) {
        this.queryParams.instId = value;
        if (value != "") {
          let params = {}
          params.instId = value;
          this.$get('/admin/mcmp/bMchntBaseInfo', {...params}).then((r) => {

            this.dataSource = r.data.rows;
            this.search();
          })
        }
      },

      viewMerchantDelay(record) {
        if (record.mchntDelayFlag === 'N' ) {
          this.$message.warning('解除延迟的数据不能再解除延迟')
        } else {
          this.isShow = true
          this.tempId = record.id
        }
      },

      handleOk() {
        let param = {}
        param.optFlag = 'release'
        param.id = this.tempId
        this.$put('/admin/mcmp/bMchntBaseInfo', param).then((r) => {
          this.isShow = false;
          this.$message.success('解除延迟成功')
          this.search()
        }).catch(() => {
          this.loading = false
        })
      },
      handleCancel() {
        this.isShow = false;
      },

      handleMerchantDelayInfoClose() {
        this.merchantDelayOperation.visiable = false
      },
      handleMerchantDelayInfoSuccess() {
        this.$message.success('新增延迟清算成功')
        this.merchantDelayOperation.visiable = false
        this.search()
      },
      editMerchantDelay(record) {
        if (record.mchntDelayFlag === 'Y' ) {
          this.$message.warning('延迟清算的数据不能再延迟清算')
        } else {

          this.$refs.merchantDelayEdit.setMerchantDelayFormValues(record)
          this.merchantDelayOperation.visiable = true
        }
      },

      search() {
        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }

        let {sortedInfo, filteredInfo} = this
        let sortField, sortOrder
        // 获取当前列的排序和列的过滤规则
        if (sortedInfo) {
          sortField = sortedInfo.field
          sortOrder = sortedInfo.order
        }
        let params = this.queryParams

        this.fetch({
          sortField: sortField,
          sortOrder: sortOrder,
          ...params,
          ...filteredInfo
        })
      },
      reset() {
        // 取消选中
        this.selectedRowKeys = []
        // 重置分页
        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }
        // 重置列排序规则
        this.sortedInfo = null
        // 重置查询参数
        this.queryParams = {}
        // // 清空时间选择
        // this.$refs.createTime.reset()
        this.fetch()
      },
      handleTableChange(pagination, filters, sorter) {
        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }

        // 将这三个参数赋值给Vue data，用于后续使用
        this.paginationInfo = pagination
        this.filteredInfo = filters
        this.sortedInfo = sorter
        // this.userInfo.visiable = false

        this.fetch({
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...this.queryParams,
          ...filters
        })
      },
      fetch(params = {}) {
        this.loading = true
        if (this.paginationInfo) {
          // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
          this.$refs.TableInfo.pagination.current = this.paginationInfo.current
          this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
          params.pageSize = this.paginationInfo.pageSize
          params.pageNum = this.paginationInfo.current
        } else {
          // 如果分页信息为空，则设置为默认值
          params.pageSize = this.pagination.defaultPageSize
          params.pageNum = this.pagination.defaultCurrent
        }
        this.$get('/admin/mcmp/bMchntBaseInfo', {
          ...params
        }).then((r) => {
          let data = r.data
          const pagination = {...this.pagination}
          pagination.total = data.total
          this.dataSource = data.rows
          this.pagination = pagination
          this.loading = false
        })
      },
    }
  }
</script>

<style lang="less" scoped>
  @import "../../../../../../static/less/Common";
</style>

